<?php

namespace app\command;

use think\facade\Log;
use think\worker\Server;
use Workerman\Lib\Timer;

class Worker extends Server
{
    protected $protocol = 'websocket';
    protected $port     = '1315';
    protected $worker;
    protected $option   = [
        'name' => 'chat1',
        'count'=> 10,
        'uidConnections' => [],
    ];

    public function onWorkerStart(): void
    {
        $time_interval = 2;
        global $worker;
        Timer::add($time_interval, static function () use ($worker) {
//            echo "心跳...".date("Y-m-d H:i:s")."\n";
        });

        $inner_text_worker = new \Workerman\Worker('text://127.0.0.1:6666');
        //这里的$connection是给推送者调用的
        $inner_text_worker->onMessage = static function ($connection, $buffer) {
            $connection->send( '你好欢迎你');
        };
        try {
            $inner_text_worker->listen();
        } catch (\Exception $e) {

        }
    }

    public function onMessage($connection,$info)
    {
        global $worker;
        $connection->send(111);
        $this->bin_uid($connection,$info);
        print_r($worker->uidConnections);
    }


    //绑定uid
    public static function bin_uid($conn,$uid): void
    {
        global $worker;
        $conn->uid  = $uid;
        $worker->uidConnections[$conn->uid] = $conn;;
    }

    //uid绑定组ID
    public static function bin_group($conn,$group_id,$uid): void
    {
        global $worker;
        $conn->group_id  = $group_id;
        $worker->uidConnections[$group_id][$uid] = $conn;;
    }



    public static function sendMessageByLive($room_id, $message ,$info): bool{
        global $worker;
        if(empty($room_id) || empty($message)){
            return false;
        }
        //验证用户数据
        if (empty($info)){
            return  false;
        }
        //需要遍历在本直播间用户给每个用户推送聊天内容
        if (isset($worker->uidConnections[$room_id])){
            foreach ($worker->uidConnections[$room_id] as $connection) {
                $connection->send(8989);
            }
        }
        return false;
    }

    public function onError($connection): void
    {
        $connection->send('连接断开................'.date('Y-m-d H:i:s'));
        Log::info('Exception IM1Close:'.date('Y-m-d H:i:s'));
    }

    public function onClose($connection): void
    {
        global $worker;
        if (isset($connection->roomId)) {
            foreach ($worker->uidConnections[$connection->roomId] as $sen) {
                $sen->send($connection->nick . '走了');
            }
            //退出关闭链接
            if ($connection->uid) {
                unset($worker->uidConnections[$connection->roomId][$connection->uid]);
            }
        }
    }
}